package com.jgybzx.listener;


import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.fastjson.JSON;
import com.jgybzx.entity.Staff;
import com.jgybzx.service.StaffService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

public class StaffListener implements ReadListener<Staff> {
    private final Logger log = LoggerFactory.getLogger(this.getClass());

    /**
     * 每隔5条存储数据库，实际使用中可以100条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 100;
    /**
     * 缓存的数据
     */
    private List<Staff> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
    @Autowired
    private StaffService staffService;

    public StaffListener(StaffService staffService) {
        this.staffService = staffService;
    }

    @Override
    public void invoke(Staff staff, AnalysisContext analysisContext) {
        log.info("解析到一条数据:{}", JSON.toJSONString(staff));
        cachedDataList.add(staff);
        // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
        if (cachedDataList.size() >= BATCH_COUNT) {
            saveData();
            // 存储完成清理 list
            cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        // 这里也要保存数据，确保最后遗留的数据也存储到数据库
        saveData();
        log.info("所有数据解析完成！");
    }

    private void saveData() {
        log.info("{}条数据，开始存储数据库！", cachedDataList.size());
        staffService.batchInsert(cachedDataList);
        log.info("存储数据库成功！");
    }
}
